﻿using AutoMapper;
using MediatR;
using Traceable.App.Application.Command.Aquaculture;
using Traceable.Domian;
using Traceable.ErrorCode;
using Traceable.Infastructure;

namespace Traceable.App.Application.Handler.Aquaculture
{
    public class CreateImmunityHandler : IRequestHandler<CreateImmunityCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Immunity_Table> _immunityRepo;
        private readonly IMapper _mapper;

        public CreateImmunityHandler(IBaseRepository<Immunity_Table> immunityRepo, IMapper mapper)
        {
            _immunityRepo = immunityRepo;
            _mapper = mapper;
        }

        /// <summary>
        /// 免疫新增
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(CreateImmunityCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

             var immunity = _immunityRepo.GetAll().Where(p => p.Id == request.Id && !p.IsDelete).FirstOrDefault();
             if(immunity==null)
             {
                var model = _mapper.Map<Immunity_Table>(request);
                model.CreateTime = DateTime.Now;
                model.Creater = "张三";
                model.UpdateTime = null;

                var res = _immunityRepo.Add(model);
                if (res > 0)
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "保存成功";
                    return Task.FromResult(result);
                }
                else
                {
                    result.Code = StatusEnum.Fail;
                    result.Data = res;
                    result.Message = "保存失败";
                    return Task.FromResult(result);
                }
             }
             else
             {
                immunity = _mapper.Map(request, immunity);
                var res =_immunityRepo.Update(immunity);
                if (res > 0)
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "修改成功";
                    return Task.FromResult(result);
                }
                else
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "修改失败";
                    return Task.FromResult(result);
                }

             }
        }
    }
}
